from utils import *
import pyximport
pyximport.install()
import pwFunc
import pylab
import os

def Labels(f):
    chunks=f.split('_')
    last=chunks.index('repeat')
    return chunks[1:last]

def DistinctLabel(f,files,sep='.'):
    common_labels=set.intersection(*tuple(map(lambda x:set(Labels(x)),files)))
    dlabels=set(Labels(f))-common_labels
    ldlabels=sorted(list(dlabels))
    return sep.join(ldlabels)

def lsSlope(x,y):
    xm=numpy.mean(x)
    ym=numpy.mean(y)
    return numpy.dot(y-ym,x-xm)/numpy.dot(x-xm,x-xm)

def printParams(params,S,xm,ym,Unit=1,label="",extra=False):
    N=(len(params)-1)/2
    M=len(S)
    xm_rate=1.0/lsSlope(xm,ym)
    Reff=1.0/(1.0/params[0]+1.0/xm_rate)
    #print 
    print "R:%s\t %4.3f[%4.3f]\t  R_0:%4.3f[%4.3f]\t Reff:%4.3f[%4.3f]"%\
        (label,params[0],params[0]/Unit, xm_rate,xm_rate/Unit,Reff,Reff/Unit)
    if extra:
        for i in range(N):
            print "range:\t [%4.1f, %4.1f]\t t0:\t %4.3f\t  \t mode:\t %4.3f\t"%\
                  (S[i],S[i+1],params[i+1],1.0/params[N+i+1])


if __name__=='__main__':
    ResultsDict=load('ResultsDict.pickle')
    files=ResultsDict.keys()
    Unit=0.012
    psize=1

    fig=pylab.figure(num=6,figsize=(15,8))
    pylab.ion()
    pylab.clf()
    pylab.grid(True)
    pylab.xlabel('Size[MB]')
    yl='Time[seek]' if Unit<1 else 'Time[s]'
    pylab.ylabel(yl)
    FigLabel="WTC"
    Title="Expected Time"
    #Title="Most probable Time"
    #Title="Min Time"

    res={}
    #print "Slope \t Avg"
    for File in files:
        S,params=ResultsDict[File]
        X=numpy.linspace(S.min(),S.max(),300)
        Y=pwFunc.gExpectedFunc(X,S,params)
        Ymode=pwFunc.gModeFunc(X,S,params)
        Ymin=pwFunc.gMinFunc(X,S,params)
        #y=Ymin
        y=Y
        slope=lsSlope(X,y)
        pylab.plot(X,y,'-',label=('Avg, %4.3f %s:%s'%(slope,FigLabel,DistinctLabel(File,files))),linewidth=1.0)
        #pylab.plot(X,y,'-',label=('Mode, %4.3f %s:%s'%(slope,FigLabel,DistinctLabel(File,files))),linewidth=1.0)
        #pylab.plot(X,y,'-',label=('Min,%4.3f, %s:%s'%(slope,FigLabel,DistinctLabel(File,files))),linewidth=1.0)
        res[DistinctLabel(File,files)]=(X,Ymin,Ymode,Y)
        #print "%4.3f \t %4.3f\t %s"%(slope,numpy.mean(y),DistinctLabel(File,files))
        n=(len(params)-1)/2
        xEx=(S[:-1]+S[1:])*0.5
        yEx=params[1:n+1]
        xm_rate=1.0/lsSlope(xEx,yEx)    
        Rm=1.0/(1.0/params[0]+1.0/(xm_rate))
        print DistinctLabel(File,files)," \t ",

        printParams(params,S,xEx,yEx,Unit=Unit,label="")
        #FigLabel+":avg")

    pylab.legend(prop={'size':8},loc='best')
    pylab.title(Title)
    pylab.draw()
    figname=os.path.join('Plots',"Comparison-%s-%s-%s.pdf"%(Title,yl,FigLabel))
    pylab.savefig(figname)
    figname=os.path.join('Plots',"Comparison-%s-%s-%s.png"%(Title,yl,FigLabel))
    pylab.savefig(figname)
